// JWT 验证守卫
import type { ExecutionContext } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import type { Observable } from 'rxjs';
import { IS_PUBLIC_KEY_ADMIN } from './public.decorator';
import { BusinessException } from 'src/common/exceptions/business.exception';

@Injectable()
export class JwtAuthGuardAdmin extends AuthGuard('adminJwt') {
  constructor(private reflector: Reflector) {
    super();
  }
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(
      IS_PUBLIC_KEY_ADMIN,
      [context.getHandler(), context.getClass()],
    );

    if (isPublic) return true;
    const request = context.switchToHttp().getRequest();
    if (!request.headers.token) {
      BusinessException.throwForbidden('抱歉哦，您无此管理权限');
    }

    return super.canActivate(context);
  }
  handleRequest(err, user, info) {
    // 根据具体的情况，你可能想要调整这些条件
    if (err) {
      BusinessException.throwForbidden();
    }
    return user;
  }
}
